/*
 * vite配置
 */
import { loadEnv } from 'vite'
import type { UserConfig, ConfigEnv } from 'vite'
import { resolve } from 'path'
// 插件
import Plugins from './vite/plugins'
import customVariables from './src/theme/custom-variables'

const root = process.cwd()
function pathResolve(dir: string) {
  return resolve(root, './', dir)
}

export default ({ mode }: ConfigEnv): UserConfig => {
  const env = loadEnv(mode, pathResolve('./vite/env'))

  return {
    base: env.VITE_BASE_PATH,
    envDir: './vite/env',
    resolve: {
      alias: [
        {
          find: '@',
          replacement: pathResolve('src')
        }
      ]
    },
    // 服务端渲染
    server: {
      host: '0.0.0.0',
      port: 8081,
      proxy: {
        '/api': {
          // target: 'https://erp.xianlian.cc/',
          target: 'https://vkerp.dtveek.com/',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '/company')
        }
      }
    },
    // 插件
    plugins: Plugins,
    // 依赖预构建
    optimizeDeps: {
      include: ['ant-design-vue/es/locale/zh_CN', 'dayjs/locale/zh-cn', 'ant-design-vue/es/locale/en_US'],
      exclude: ['vue-demi']
    },
    // 打包构建配置
    build: {
      // 清除console和debugger
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true
        }
      },
      rollupOptions: {
        output: {
          // 配置这个是让不同类型文件放在不同文件夹，不会显得太乱
          chunkFileNames: 'js/[name]-[hash].js',
          entryFileNames: 'js/[name]-[hash].js',
          assetFileNames: '[ext]/[name]-[hash].[ext]',
          manualChunks(id) {
            //静态资源分拆打包
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString()
            }
          }
        }
      },
      target: 'modules',
      outDir: 'dist', // 指定输出路径
      assetsDir: 'assets', // 指定生成静态文件目录
      assetsInlineLimit: 4096, // 小于此阈值的导入或引用资源将内联为 base64 编码
      chunkSizeWarningLimit: 500, // chunk 大小警告的限制
      minify: 'terser', // 混淆器，terser构建后文件体积更小
      emptyOutDir: true //打包前先清空原有打包文件
    },
    css: {
      preprocessorOptions: {
        less: {
          modifyVars: customVariables,
          javascriptEnabled: true
        }
      }
    },
    define: {
      __INTLIFY_PROD_DEVTOOLS__: false,
      'process.env': process.env
    }
  }
}
